package com.cy.study.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cy.study.common.BasePageReq;
import com.cy.study.common.Response;
import com.cy.study.entity.MajorEntity;
import com.cy.study.entity.UserInfoEntity;
import com.cy.study.exception.BusinessException;
import com.cy.study.mapper.MajorMapper;
import com.cy.study.mapper.UserInfoMapper;
import com.cy.study.req.*;
import com.cy.study.res.*;
import com.cy.study.service.*;
import com.cy.study.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import static com.cy.study.common.CommonConstant.FILE_PATH;

/**
 * 用户端个人中心
 */
@RequiredArgsConstructor
@RequestMapping("/userCenter")
@RestController
@CrossOrigin
@Slf4j
public class UserCenterController {

    private final ExperienceService experienceService;
    private final FileService fileService;
    private final ExamService examService;

    private final UserInfoMapper userInfoMapper;
    private final MajorMapper majorMapper;
    private final UserInfoService userInfoService;
    private final PushRecordService pushRecordService;


    /**
     * 用户中心新增论坛心得
     * @param req
     * @return
     */
    @PostMapping("/userCenterAddExperience")
    public Response<Integer> userCenterAddExperience(@RequestBody UserCenterAddExperienceReq req){
        Integer id = experienceService.userCenterAddExperience(req);
        return Response.success(id);
    }

    /**
     * 用户中心心得论坛列表
     * @param req
     * @return
     */
    @PostMapping("/userCenterExperiencePage")
    public Response<Page<UserCenterExperiencePageRes>> userCenterExperiencePage(@RequestBody BasePageReq req){
        Page<UserCenterExperiencePageRes> info = experienceService.userCenterExperiencePage(req);
        return Response.success(info);
    }

    /**
     * 用户中心更新论坛心得
     * @param req
     * @return
     */
    @PostMapping("/userCenterUpdateExperience")
    public Response userCenterUpdateExperience(@RequestBody UserCenterUpdateExperienceReq req){
        experienceService.userCenterUpdateExperience(req);
        return Response.success();
    }

    /**
     * 用户中心删除论坛心得
     * @param req
     * @return
     */
    @PostMapping("/userCenterDeleteExperience")
    public Response userCenterDeleteExperience(@RequestBody UserCenterDeleteExperienceReq req){
        experienceService.userCenterDeleteExperience(req);
        return Response.success();
    }

//-----------------------------资源

    /**
     * 用户中心新增资源
     * @param req
     * @return
     */
    @PostMapping("/userCenterAddFile")
    public Response<Integer> userCenterAddFile(@RequestBody UserCenterAddFileReq req){
        Integer id = fileService.userCenterAddFile(req);
        return Response.success(id);
    }

    /**
     * 上传资源文件，在新上传文件的时候先调用
     * @param file
     * @return
     */
    @PostMapping("/uploadFile")
    @ResponseBody
    public Response<String> addFile(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()){
            return Response.serverError("文件上传失败");
        }
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //生成文件名称通用方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = tempName.toString();
        try {
            //保存文件
            byte[] bytes = file.getBytes();
            Path path = Paths.get(FILE_PATH+newFileName);
            Files.write(path,bytes);
        }catch (IOException e){
            e.printStackTrace();
        }
        return Response.success(tempName.toString());
    }

    /**
     * 用户中心资源列表
     * @param req
     * @return
     */
    @PostMapping("/userCenterFilePage")
    public Response<Page<UserCenterFilePageRes>> userCenterFilePage(@RequestBody BasePageReq req){
        Page<UserCenterFilePageRes> res = fileService.userCenterFilePage(req);
        return Response.success(res);
    }

    /**
     * 用户中心更新资源
     * @param req
     * @return
     */
    @PostMapping("/userCenterUpdateFile")
    public Response userCenterUpdateFile(@RequestBody UserCenterUpdateFileReq req){
        fileService.userCenterUpdateFile(req);
        return Response.success();
    }

    /**
     * 用户中心删除资源
     * @param req
     * @return
     */
    @PostMapping("/userCenterDeleteFile")
    public Response userCenterDeleteFile(@RequestBody UserCenterDeleteFileReq req){
        fileService.userCenterDeleteFile(req);
        return Response.success();
    }

    //-------------------------练习

    /**
     * 个人中心试卷列表
     * @return
     */
    @PostMapping("/userCenterPageExam")
    public Response<Page<UserCenterPageExamRes>> userCenterPageExam(@RequestBody BasePageReq req){
        Page<UserCenterPageExamRes> res = examService.userCenterPageExam(req);
        return Response.success(res);
    }

    /**
     * 个人中心试卷详情
     * @param examRecordId
     * @return
     */
    @GetMapping("/userCenterExamDetail/{examRecordId}")
    public Response<CenterExamRes> userCenterExamDetail(@PathVariable Integer examRecordId){
        CenterExamRes res = examService.userCenterExamDetail(examRecordId);
        return Response.success(res);
    }


    //--------------------------------------用户中心推送

    /**
     * 用户中心推送列表
     * @param req
     * @return
     */
    @PostMapping("/userCenterPagePush")
    public Response<Page<UserCenterPagePushRes>> userCenterPagePush(@RequestBody BasePageReq req){
        Page<UserCenterPagePushRes> res = pushRecordService.userCenterPagePush(req);
        return Response.success(res);
    }


    /**
     * 用户推送详情
     * @param pushId
     * @return
     */
    @GetMapping("/userCenterPushDetail/{pushId}")
    public Response<UserCenterPushDetailRes> userCenterPushDetail(@PathVariable Integer pushId){
        UserCenterPushDetailRes res = pushRecordService.userCenterPushDetail(pushId);
        return Response.success(res);
    }


    /**
     * 用户个人信息
     * @return
     */
    @GetMapping("/infoDetail")
    public Response<UserCenterInfoDetailRes> infoDetail(){
        Integer userId = SecurityUtils.getUserId();
        UserInfoEntity userInfoEntity = userInfoMapper.selectById(userId);
        UserCenterInfoDetailRes res = new UserCenterInfoDetailRes();
        BeanUtils.copyProperties(userInfoEntity,res);
        MajorEntity majorEntity = majorMapper.selectById(userInfoEntity.getMajorId());
        if(majorEntity==null){
            throw new BusinessException("专业不存在，请检查");
        }
        res.setMajorName(majorEntity.getMajorName());
        return Response.success(res);
    }


    /**
     * 用户修改用户信息
     * @param req
     * @return
     */
    @PostMapping("/updateInfo")
    public Response updateInfo(@RequestBody UserUpdateInfoReq req){
        userInfoService.updateInfo(req);
        return Response.success();
    }

    /**
     * 用户修改密码
     * @param req
     * @return
     */
    @PostMapping("/updatePassword")
    public Response updatePassword(@RequestBody UserUpdatePasswordReq req){
        userInfoService.updatePassword(req);
        return Response.success();
    }

    /**
     * 更新用户头像
     * @param file
     * @return
     */
    @PostMapping("/uploadPic")
    public Response uploadPic(@RequestParam("file") MultipartFile file){
        userInfoService.uploadPic(file,null,true);
        return Response.success();
    }

}
